const axios = require('axios');
const cheerio = require('cheerio'); // 爬虫

// 配置请求参数
const config = {
  MOJI_HOST: "https://tianqi.moji.com/weather/china/", // 墨迹天气网站
  CITY: "chongqing", // 天气城市
  LOCATION: "wanzhou-district", // 天气具体区域
  ONE:'http://wufazhuce.com/', // ONE的web版网站
};

// 获取每日一句
async function getOne() { // 获取每日一句
  let res = await axios.get(config.ONE, {timeout: 0});
  let $ = cheerio.load(res.data);
  let todayOneList = $('#carousel-one .carousel-inner .item')
  let todayOne = $(todayOneList[0]).find('.fp-one-cita').text().replace(/(^\s*)|(\s*$)/g, "")
  return todayOne;
};

// 获取墨迹天气信息
async function getWeather() {
  let url = config.MOJI_HOST+config.CITY+'/'+config.LOCATION
  const res = await axios.get(url, {timeout: 0});
  let $ = cheerio.load(res.data);
  let weatherTips = $('.wea_tips em').text();
  const today = $('.forecast .days').first().find('li');
  let todayInfo = {
	  Day:$(today[0]).text().replace(/(^\s*)|(\s*$)/g, ""),
	  WeatherText:$(today[1]).text().replace(/(^\s*)|(\s*$)/g, ""),
	  Temp:$(today[2]).text().replace(/(^\s*)|(\s*$)/g, ""),
	  Wind:$(today[3]).find('em').text().replace(/(^\s*)|(\s*$)/g, ""),
	  WindLevel:$(today[3]).find('b').text().replace(/(^\s*)|(\s*$)/g, ""),
	  PollutionLevel:$(today[4]).find('strong').text().replace(/(^\s*)|(\s*$)/g, "")
  }
  let obj = {
    weatherTips: weatherTips,
    todayWeather: todayInfo.Day + ':' + todayInfo.WeatherText + '\n' + '温度:' + todayInfo.Temp +  '\n' + todayInfo.Wind + todayInfo.WindLevel + '\n' + '空气:' + todayInfo.PollutionLevel + '\n'
  }
  return  obj
};

// 获取当前时间
function getToday() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hour = now.getHours().toString().padStart(2, '0');
  const minute = now.getMinutes().toString().padStart(2, '0');
  const second = now.getSeconds().toString().padStart(2, '0');
  const formattedDate = `${year}年${month}月${day}日`;
  const formattedTime = `${hour}:${minute}:${second}`;
  const formattedDateTime = `${formattedDate} ${formattedTime}`;

  return formattedDateTime;
};

// 处理定时发送的消息
async function handleSendMessage() {
  let one = await getOne();
  let weather = await getWeather();
  let today = await getToday();

  let str = '早上好！爸爸妈妈～～\n今天是' + today + '\n\n万州天气:\n\n' + weather.weatherTips + '\n\n' + weather.todayWeather + '\n每日一句:\n\n' + one + '\n\n' + '------来自宝贝儿子';
  return str;
};

module.exports = {
  getWeather,
  getOne,
  getToday,
  handleSendMessage
}